/**
 * 自定义节点重叠
 * @author houjinhui
 */
import G6 from '@antv/g6'
import { message } from 'ant-design-vue'

interface KeyValue {
  [key: string]: any
}

/**
 * 自定义画布布局
 */
export default function registerRotateLayout() {
  // 基础弧线布局
  G6.registerLayout('rotating', {
    angle: 90,
    // 定义自定义行为的默认参数，会与用户传入的参数进行合并
    getDefaultCfg() {
      return {}
    },
    /**
     * 初始化
     * @param {Object} data 数据
     */
    init(data: any) {
      const currentLayout = this // this 指向当前布局
      currentLayout.nodes = data.nodes
      currentLayout.edges = data.edges
    },
    /**
     * 执行布局
     */
    execute() {
      const currentLayout: any = this
      const { nodes, angle } = currentLayout
      const rotationAngle: number = angle || 90
      const nodesLength: number = nodes.length
      // const nodesLength = nodes.length  // 节点数量
      // 为每一个节添加布局信息
      try {
        // 旋转中心
        let xMean = 0
        let yMean = 0
        nodes.forEach((node: any) => {
          xMean += node.x
          yMean += node.y
        })
        xMean /= nodesLength
        yMean /= nodesLength

        // 旋转
        const radian: any = (Math.PI / 180) * rotationAngle
        nodes.forEach((node: any) => {
          const { x, y } = node
          const newX: number =
            (x - xMean) * Math.cos(radian) -
            (y - yMean) * Math.sin(radian) +
            xMean
          const newY: number =
            (x - xMean) * Math.sin(radian) +
            (y - yMean) * Math.cos(radian) +
            yMean
          // const newX: number = (x - rx0)*cos(a) - (y - ry0)*sin(a) + rx0
          // const newY: number = (x - rx0)*sin(a) + (y - ry0)*cos(a) + ry0
          node.x = newX
          node.y = newY
        })
      } catch {
        message.error('布局失败！')
      }
    },

    /**
     * 根据传入的数据进行布局
     * @param {Object} data 数据
     */
    layout(data: any) {
      const currentLayout = this
      currentLayout.init(data)
      currentLayout.execute()
    },
    /**
     * 更新布局配置，但不执行布局
     * @param {Object} cfg 需要更新的配置项
     */
    updateCfg(cfg: any) {
      const currentLayout = this
      G6.Util.mix(currentLayout, cfg)
    },
    /**
     * 销毁
     */
    destroy() {
      const currentLayout = this
      currentLayout.positions = null
      currentLayout.nodes = null
      currentLayout.edges = null
      currentLayout.destroyed = true
    },
  })
}
